package com.secneo.appshare.threads;

import java.io.ByteArrayOutputStream;

import weibo4android.User;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.http.AccessToken;
import weibo4android.http.HttpClient;
import weibo4android.http.RequestToken;
import weibo4android.http.Response;
import weibo4android.org.json.JSONException;
import weibo4android.org.json.JSONObject;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.secneo.appshare.R;
import com.secneo.appshare.activities.OAuthConstant;
import com.secneo.appshare.api.LocalStore;
import com.secneo.appshare.api.RemoteApi.UserInfo;
import com.secneo.appshare.api.impl.RemoteApiImpl;
import com.secneo.appshare.common.ActivityUtil;
import com.secneo.appshare.common.Constants;

// step 1  获得request token
public class LoginWeiboThread extends Thread {

	private Handler handler;
	private Context ctx;
	private String account;
	private String password;
	private boolean shareToFans;
	
	public LoginWeiboThread(Context ctx, Handler handler, String account, String password, boolean share) 
	{
		this.ctx = ctx;
		this.handler = handler;
		this.account = account;
		this.password = password;
		this.shareToFans = share;
	}
	
	public void run() 
	{
		try 
		{
			Log.d("MyTag", "No AccessToken, try to get it");
			System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
			System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
			Weibo weibo = new Weibo();
			RequestToken requestToken;
			try
			{
				requestToken = weibo.getOAuthRequestToken();
				
				String url = requestToken.getAuthenticationURL() + "&oauth_callback=json&display=page&userId="+account+"&passwd="+password;
				HttpClient http = new HttpClient();
				Response res = http.get(url);
				if (res == null) 
				{
					Message msg = new Message();
					msg.what = Constants.MSG_LOGIN_FAILED;
					handler.sendMessage(msg);
					return;
				}
				
				String oauth_verifier = null;
		    	JSONObject json=res.asJSONObject();
		    	try 
		    	{
					oauth_verifier = json.getString("oauth_verifier");

				} catch (JSONException je) {
					Message msg = new Message();
					msg.what = Constants.MSG_LOGIN_FAILED;
					handler.sendMessage(msg);
					Log.d("MyTag", "JSONException: "+je.getMessage());
					return;
				}
				
				AccessToken accessToken = requestToken.getAccessToken(oauth_verifier);
				OAuthConstant.getInstance().setAccessToken(accessToken);
				String token  = accessToken.getToken();
				String tokenSecret = accessToken.getTokenSecret();
				
				SharedPreferences sp = ctx.getSharedPreferences(Constants.PRE_USER_INFO, 0);
				sp.edit().putString(Constants.ACCESS_TOKEN, token).commit();
				sp.edit().putString(Constants.ACCESS_TOKEN_SECRET, tokenSecret).commit();
				
				LocalStore.getLocaleStoreInstance(ctx).getSinaUserInfo();
				User user = weibo.verifyCredentials();
				Log.d("MyTag", "Sina id = " + user.getId());
				Log.d("MyTag", "Sina name = " + user.getScreenName());
				Log.d("MyTag", "Sina image = " + user.getProfileImageURL());
				
				boolean first_login = (LocalStore.getLocaleStoreInstance(ctx).getAndroidId() == null ||
						LocalStore.getLocaleStoreInstance(ctx).getAndroidId() == "") ? true : false ;
				
				RemoteApiImpl remoteApi = new RemoteApiImpl();
				UserInfo ret = null;
				String localName = LocalStore.getLocaleStoreInstance(ctx).getNickName();
				String localIcon = LocalStore.getLocaleStoreInstance(ctx).getAvatarName();
				if(localName.equals(""))
					ret = remoteApi.addNewWeiboUser(ctx, 1, String.valueOf(user.getId()), user.getScreenName(), user.getProfileImageURL().toString());
				else
					ret = remoteApi.addNewWeiboUser(ctx, 1, String.valueOf(user.getId()), localName, localIcon);
				
				if (ret == null) 
					Log.d("MyTag", "Register sina weibo user failed!");
				else
				{
					if(ret.id == Constants.SNS_HAS_ASSOCIATE || ret.id.equals(Constants.SNS_HAS_ASSOCIATE)){
						//账号已经绑定过
						LocalStore.getLocaleStoreInstance().logoutSinaAccount();
						
						Message msg = new Message() ;
						msg.what = 5;
						Bundle data = new Bundle() ;
						data.putString("nickName", user.getScreenName()) ;
						msg.setData(data) ;
						handler.sendMessage(msg) ;
						return ;
					}
					Log.d("MyTag", "Register sina weibo user success!");
					LocalStore.getLocaleStoreInstance().setSinaAccountActive();
					if(ret.id != null && !"".equals(ret.id))
					{
						LocalStore.getLocaleStoreInstance(ctx).setUid(ret.id);
						LocalStore.getLocaleStoreInstance(ctx).setAndroidId(ret.androidId);
					}
					sp.edit().putString(Constants.USER_ID, String.valueOf(user.getId())).commit();
					sp.edit().putString(Constants.USER_NAME, user.getScreenName()).commit();
					sp.edit().putString(Constants.USER_IMAGE, user.getProfileImageURL().toString()).commit();
					
					if(localName.equals(""))
					{
					//	LocalStore.getLocaleStoreInstance(ctx).setNickName(user.getScreenName());
					//	LocalStore.getLocaleStoreInstance(ctx).setAvatarName(user.getProfileImageURL().toString());
						LocalStore.getLocaleStoreInstance(ctx).setNickName(ret.nick);
						LocalStore.getLocaleStoreInstance(ctx).setAvatarName(user.getProfileImageURL().toString());
					}
				}
				
				Message msg = new Message();
				msg.what = Constants.MSG_LOGIN_SUCCESS;
				Bundle data = new Bundle() ;
				data.putBoolean("first_login", first_login) ;
				msg.setData(data) ;
				handler.sendMessage(msg);
				
				if(shareToFans)
				{
					Bitmap bmp = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.icon);
		            ByteArrayOutputStream baos = new ByteArrayOutputStream();
		            bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
		            byte[] content = baos.toByteArray();
					ActivityUtil.shareToWeibo(ctx, Constants.UPLOAD_ACTION_LOGIN, null, null, content, null, "", null, null);
					bmp.recycle();bmp = null;
				}
				return;

			} catch (WeiboException e)
			{
				Log.d("MyTag", "WeiboException: "+e.getMessage());
				Message msg = new Message();
				msg.what = Constants.MSG_LOGIN_FAILED;
				handler.sendMessage(msg);
				return;
			}
			
		} catch (Exception ex) {
			Log.d("MyTag", "Exception: "+ex.getMessage());
			Message msg = new Message();
			msg.what = Constants.MSG_LOGIN_FAILED;
			handler.sendMessage(msg);
			return;
		}
	}
}
